//
//  WBOAuthViewController.swift
//  CFZWeiBo
//
//  Created by Cedric Zheng on 26/11/2016.
//  Copyright © 2016 Cedric Zheng. All rights reserved.
//

import UIKit

class WBOAuthViewController: UIViewController {
    
    /// A cancel button on the left side of navigation bar
    lazy var leftBarButtonItem: UIBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(cancel))
    
    lazy var webView: UIWebView = {
        let webView: UIWebView = UIWebView(frame: self.view.bounds)
        webView.delegate = self
        webView.scrollView.bounces = false
        return webView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.white
        
        setupUI()
    }
    
}

// MARK: - Setup methods
extension WBOAuthViewController {
    func setupUI() {
        navigationItem.leftBarButtonItem = leftBarButtonItem
        view.addSubview(webView)
        
        // Load Oauth page for user to login to OAuth server
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectURI)"
        if let url = URL(string: urlString) {
            let request = URLRequest(url: url)
            webView.loadRequest(request)
        }
    }
}

// MARK: - Private methods
extension WBOAuthViewController {
    
    /// Dismiss current view controller
    @objc fileprivate func cancel() {
        dismiss(animated: true, completion: nil)
    }
}

// MARK: - Delegates
extension WBOAuthViewController: UIWebViewDelegate {
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlR = request.url
        let urlStringR = urlR?.absoluteString
        
        // Find out if the page is from redirectURI
        guard let urlString = urlStringR, urlString.hasPrefix(redirectURI) else {
            return true
        }
        
        // Find out if the page has 'code' in query
        guard let query = urlR?.query, query.hasPrefix("code=") else {
            cancel()
            return false
        }
        
        let code = query.substring(from: "code=".endIndex)
        // Use the code to gain access token
        networkToolShared.requestAccessToken(code: code) { (responseObject) in
            guard
                let responseObject  = responseObject,
                let accessTokenDict = responseObject as? [String: Any],
                let access_token    = accessTokenDict["access_token"] as? String,
                let uid             = accessTokenDict["uid"] as? String
                else {
                    self.cancel()
                    return
            }
            // Use the token to gain user data
            networkToolShared.requestUserAccount(access_token: access_token, uid: uid) { (responseObject) in
                guard
                    var userDict = responseObject as? [String: Any] else {
                        self.cancel()
                        return
                }
                
                // Add accessTokenDict to userDict, save login info for next time
                for (k, v) in accessTokenDict {
                    userDict[k] = v
                }
                
                userAccountShared.save(userDict)
                
                defaultNotiCenter.post(loginSuccessNotification)
                
                self.cancel()
            }
        }
        return false
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        // Write user name and password into OAuth server login page for convenience, should be removed later
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '13715395890'; document.getElementById('passwd').value = 'a12345';")
    }
    
}


